package com.dominator.utils.pay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.dominator.utils.encode.Des3Utils;

/**
 * HttpKit
 */
public class HttpKit {

	private HttpKit() {
	}

	/**
	 * https 域名校验
	 */
	private class TrustAnyHostnameVerifier implements HostnameVerifier {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}

	/**
	 * https 证书管理
	 */
	private class TrustAnyTrustManager implements X509TrustManager {
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}

		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}
	}

	private static final String GET = "GET";
	private static final String POST = "POST";
	private static final String CHARSET = "UTF-8";

	private static final SSLSocketFactory sslSocketFactory = initSSLSocketFactory();
	private static final TrustAnyHostnameVerifier trustAnyHostnameVerifier = new HttpKit().new TrustAnyHostnameVerifier();

	private static SSLSocketFactory initSSLSocketFactory() {
		try {
			TrustManager[] tm = { new HttpKit().new TrustAnyTrustManager() };
			SSLContext sslContext = SSLContext.getInstance("TLS", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			return sslContext.getSocketFactory();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static HttpURLConnection getHttpConnection(String url, String method, Map<String, String> headers)
			throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
		/*
		 * URL _url = new URL(url); HttpURLConnection conn =
		 * (HttpURLConnection)_url.openConnection(); if (conn instanceof
		 * HttpsURLConnection) {
		 * ((HttpsURLConnection)conn).setSSLSocketFactory(sslSocketFactory);
		 * ((HttpsURLConnection)conn).setHostnameVerifier(
		 * trustAnyHostnameVerifier); }
		 * 
		 * conn.setRequestMethod(method); conn.setDoOutput(true);
		 * conn.setDoInput(true);
		 * 
		 * conn.setConnectTimeout(19000); conn.setReadTimeout(19000);
		 * 
		 * conn.setRequestProperty("Content-Type",
		 * "application/x-www-form-urlencoded");
		 * conn.setRequestProperty("User-Agent",
		 * "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"
		 * );
		 * 
		 * if (headers != null && !headers.isEmpty()) for (Entry<String, String>
		 * entry : headers.entrySet()) conn.setRequestProperty(entry.getKey(),
		 * entry.getValue());
		 * 
		 * return conn;
		 */

		HttpsURLConnection httpUrlConn = null;
		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL conn = new URL(url);
			httpUrlConn = (HttpsURLConnection) conn.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(method);

			// if ("GET".equalsIgnoreCase(method))
			// httpUrlConn.connect();
			return httpUrlConn;
		} catch (ConnectException ce) {
			ce.printStackTrace();
			// log.error("Weixin server connection timed out.");
			System.out.println("Weixin server connection timed out.");
		} catch (Exception e) {
			e.printStackTrace();
			// log.error("https request error:{}", e);
			System.out.println("https request error:{}");
		} finally {
			if (httpUrlConn != null)
				httpUrlConn.disconnect();
		}
		return httpUrlConn;
	}

	/**
	 * Send GET request
	 */
	public static String get(String url, Map<String, String> queryParas, Map<String, String> headers) {
		HttpURLConnection conn = null;
		try {
			System.out.println("execute=================HttpKit.get==url=" + url);
			String buildUrl = buildUrlWithQueryString(url, queryParas);
			conn = getHttpConnection(buildUrl, GET, headers);
			System.out.println("execute=================HttpKit.get==comm=" + conn);
			conn.connect();
			System.out.println("=======conn.connect()======after===");
			return readResponseString(conn);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
	}

	public static String get(String url, Map<String, String> queryParas) {
		return get(url, queryParas, null);
	}

	public static String get(String url) {
		return get(url, null, null);
	}

	/**
	 * Send POST request
	 */
	public static String post(String url, Map<String, String> queryParas, String data, Map<String, String> headers) {
		HttpURLConnection conn = null;
		try {
			conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), POST, headers);
			conn.connect();

			OutputStream out = conn.getOutputStream();
			out.write(data.getBytes(CHARSET));
			out.flush();
			out.close();

			return readResponseString(conn);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
	}

	public static String post(String url, Map<String, String> queryParas, String data) {
		return post(url, queryParas, data, null);
	}

	public static String post(String url, String data, Map<String, String> headers) {
		return post(url, null, data, headers);
	}

	public static String post(String url, String data) {
		return post(url, null, data, null);
	}

	private static String readResponseString(HttpURLConnection conn) {
		System.out.println("=====execute======readResponseString===" + conn);
		StringBuilder sb = new StringBuilder();
		InputStream inputStream = null;
		try {
			inputStream = conn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, CHARSET));
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line).append("\n");
			}
			System.out.println("=====execute======readResponseString= sb.toString()==" + sb.toString());
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * Build queryString of the url
	 */
	private static String buildUrlWithQueryString(String url, Map<String, String> queryParas) {
		if (queryParas == null || queryParas.isEmpty())
			return url;

		StringBuilder sb = new StringBuilder(url);
		boolean isFirst;
		if (url.indexOf("?") == -1) {
			isFirst = true;
			sb.append("?");
		} else {
			isFirst = false;
		}

		for (Entry<String, String> entry : queryParas.entrySet()) {
			if (isFirst)
				isFirst = false;
			else
				sb.append("&");

			String key = entry.getKey();
			String value = entry.getValue();
			if (!StringUtils.isEmpty(value))
				try {
					value = URLEncoder.encode(value, CHARSET);
				} catch (UnsupportedEncodingException e) {
					throw new RuntimeException(e);
				}
			sb.append(key).append("=").append(value);
		}
		return sb.toString();
	}

	public static String readIncommingRequestData(HttpServletRequest request) {
		BufferedReader br = null;
		try {
			StringBuilder result = new StringBuilder();
			br = request.getReader();
			for (String line = null; (line = br.readLine()) != null;) {
				result.append(line).append("\n");
			}

			return result.toString();
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			if (br != null)
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
	public static String al_get_order(Map<String,String>signMap,String url) {
		String resultContent = "";
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		
		HttpPost httpPost = new HttpPost(url);
		List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();  
		long timestamps = System.currentTimeMillis();
		formparams.add(new BasicNameValuePair("app_id", signMap.get("app_id")));
		formparams.add(new BasicNameValuePair("method", signMap.get("method")));
		formparams.add(new BasicNameValuePair("charset", signMap.get("charset")));
		formparams.add(new BasicNameValuePair("sign_type", signMap.get("sign_type")));
		formparams.add(new BasicNameValuePair("timestamp", signMap.get("timestamp")));
		formparams.add(new BasicNameValuePair("version", signMap.get("version")));
		formparams.add(new BasicNameValuePair("biz_content", signMap.get("biz_content")));
		formparams.add(new BasicNameValuePair("sign", signMap.get("sign")));
		
	    UrlEncodedFormEntity uefEntity;
		try {
			long start = System.currentTimeMillis();
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
		    httpPost.setEntity(uefEntity);   
		    System.out.println("1 "+EntityUtils.toString(httpPost.getEntity()));
		    System.out.println("2 "+"httpPost.-->"+httpPost.toString());
		    CloseableHttpResponse httpResponse = httpclient.execute(httpPost);
		    System.out.println("3 "+"httpResponse-->"+httpResponse.toString());
		    HttpEntity entity = httpResponse.getEntity();
		    System.out.println("4 "+httpResponse.getStatusLine().toString());
			if (entity != null) {
				resultContent = EntityUtils.toString(entity, "UTF-8");
				System.out.println("5\n "+resultContent);
			}
			long end = System.currentTimeMillis();
			System.out.println("cost -->"+(end -start));
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			// 关闭连接,释放资源
			try {
				if(response != null){
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultContent;
	}
	public static String al_get_order_wap(Map<String,String>signMap,String url) {
		String resultContent = "";
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		
		HttpPost httpPost = new HttpPost(url);
		List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();  
		long timestamps = System.currentTimeMillis();
		Set<String> setKey = signMap.keySet();
		for (String str : setKey) {  
			System.out.println(str+"-----------"+signMap.get(str));
			formparams.add(new BasicNameValuePair(str, signMap.get(str)));
		}  
	    UrlEncodedFormEntity uefEntity;
		try {
			long start = System.currentTimeMillis();
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
		    httpPost.setEntity(uefEntity);   
		    System.out.println("1 "+EntityUtils.toString(httpPost.getEntity()));
		    System.out.println("2 "+"httpPost.-->"+httpPost.toString());
		    CloseableHttpResponse httpResponse = httpclient.execute(httpPost);
		    System.out.println("3 "+"httpResponse-->"+httpResponse.toString());
		    HttpEntity entity = httpResponse.getEntity();
		    System.out.println("4 "+httpResponse.getStatusLine().toString());
			if (entity != null) {
				resultContent = EntityUtils.toString(entity, "UTF-8");
				System.out.println("5\n "+resultContent);
			}
			long end = System.currentTimeMillis();
			System.out.println("cost -->"+(end -start));
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			// 关闭连接,释放资源
			try {
				if(response != null){
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultContent;
	}
	public static String aplle_pay_get_order(String receipt_data,String url) {
		String resultContent = "";
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		
		HttpPost httpPost = new HttpPost(url);
		List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();  
		long timestamps = System.currentTimeMillis();
		Map<String,String> map = new HashMap<String,String>();
		map.put("receipt-data", receipt_data);
		System.out.println("************************************");
		System.err.println(Des3Utils.encResponse(map));
		formparams.add(new BasicNameValuePair("receipt-data", receipt_data));
	    UrlEncodedFormEntity uefEntity;
		try {
			long start = System.currentTimeMillis();
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
		    httpPost.setEntity(uefEntity);   
		    System.out.println("1 "+EntityUtils.toString(httpPost.getEntity()));
		    System.out.println("2 "+"httpPost.-->"+httpPost.toString());
		    CloseableHttpResponse httpResponse = httpclient.execute(httpPost);
		    System.out.println("3 "+"httpResponse-->"+httpResponse.toString());
		    HttpEntity entity = httpResponse.getEntity();
		    System.out.println("4 "+httpResponse.getStatusLine().toString());
			if (entity != null) {
				resultContent = EntityUtils.toString(entity, "UTF-8");
				System.out.println("5\n "+resultContent);
			}
			long end = System.currentTimeMillis();
			System.out.println("cost -->"+(end -start));
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			// 关闭连接,释放资源
			try {
				if(response != null){
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultContent;
	}
	
	public static String sendPostPay(String param,String url) {  
	    StringBuilder sb = new StringBuilder();  
	    PrintWriter out = null;  
	    BufferedReader in = null;  
	    Map<String,String> map = new HashMap<String,String>();
		map.put("receipt-data", param);
		System.out.println(Des3Utils.encResponse(map));
	    try {  
	        URL realUrl = new URL(url);  
	        // 打开和URL之间的连接  
	        URLConnection conn = realUrl.openConnection();  
	        // 设置通用的请求属性  
	        conn.setRequestProperty("accept", "*/*");  
	        conn.setRequestProperty("connection", "Keep-Alive");  
	        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
	        // 发送POST请求必须设置如下两行  
	        conn.setDoOutput(true);  
	        conn.setDoInput(true);  
	        // 获取URLConnection对象对应的输出流  
	        out = new PrintWriter(conn.getOutputStream());  
	        // 发送请求参数  
	        out.print(Des3Utils.encResponse(map));  
	        // flush输出流的缓冲  
	        out.flush();  
	        // 定义BufferedReader输入流来读取URL的响应  
	        in = new BufferedReader(  
	                new InputStreamReader(conn.getInputStream()));  
	        String line;  
	        sb = new StringBuilder();  
	        while ((line = in.readLine()) != null) {  
	            sb.append(line);  
	        }  
	    } catch (Exception e) {  
	        System.out.println("发送 POST 请求出现异常！"+e);  
	        e.printStackTrace();  
	    }  
	    //使用finally块来关闭输出流、输入流  
	    finally{  
	        try{  
	            if(out!=null){  
	                out.close();  
	            }  
	            if(in!=null){  
	                in.close();  
	            }  
	        }  
	        catch(IOException ex){  
	            ex.printStackTrace();  
	        }  
	    }  
	    return sb.toString();  
	}   
}